<template>
  <basic-container>
    <avue-crud ref="crud" :option="option" :data="data" :page="page" :table-loading="loading" @on-load="getList"
      @row-save="handleAdd" @row-update="handleUpdate" @row-del="handleDel" @refresh-change="refreshChange">
      <!-- 自定义操作列 -->
      <template slot="menu" slot-scope="{ row }">
        <el-button type="text" size="small" @click="handleEdit(row)">编辑</el-button>
        <el-button type="text" size="small" @click="handleDel(row)">删除</el-button>
        <el-button type="text" size="small" @click="handleStatus(row)"
          :style="{ color: row.status === 1 ? 'red' : 'green' }">
          {{ row.status === 1 ? "下架" : "上架" }}
        </el-button>
      </template>

      <!-- 自定义状态列 -->
      <template slot="status" slot-scope="{ row }">
        <el-tag :type="statusType[row.status]">
          {{ statusMap[row.status] }}
        </el-tag>
      </template>

      <!-- 自定义图片列 -->
      <template slot="image" slot-scope="{ row }">
        <el-image style="width: 100px; height: 60px" :src="row.image" :preview-src-list="[row.image]" fit="contain">
          <div slot="error" class="image-slot">
            <i class="el-icon-picture-outline"></i>
            <div>图片加载失败</div>
          </div>
        </el-image>
      </template>

      <!-- 自定义位置列 -->
      <template slot="ident" slot-scope="{ row }">
        {{ bannerType[row.ident] }}
      </template>

      <!-- 自定义正序倒序列 -->
      <template slot="sort" slot-scope="{ row }">
        <i class="el-icon-top" v-if="row.sort === 1"></i>
        <i class="el-icon-bottom" v-else></i>
      </template>
    </avue-crud>
  </basic-container>
</template>

<script>
import { getBannerList, updateBanner, addBanner, delBanner } from "./api";

export default {
  data () {
    return {
      loading: false,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      data: [],
      statusMap: {
        0: "未上架",
        1: "已上架",
        2: "已下架",
      },
      bannerType: {
        1: "首页头部",
        2: "首页底部",
      },
      statusType: {
        0: "info",
        1: "success",
        2: "warning",
      },
      option: {
        viewBtn: false,
        editBtn: false,
        delBtn: false,
        addBtn: true,
        addBtnText: "新建",
        dialogWidth: "50%",
        dialogClickModal: false,
        searchBtnText: "查询",
        searchBtnIcon: "el-icon-search",
        emptyBtnText: "重置",
        emptyBtnIcon: "el-icon-refresh",
        column: [
          {
            label: "图片",
            prop: "image",
            type: "upload",
            listType: "picture-img",
            span: 24,
            slot: true,
            align: "center",
            rules: [
              {
                required: true,
                message: "请上传图片",
                trigger: "change",
              },
              {
                validator: (rule, value, callback) => {
                  if (!value) {
                    callback(new Error("请上传图片"));
                  } else if (!value.startsWith('http')) {
                    callback(new Error("图片URL格式不正确"));
                  } else {
                    callback();
                  }
                },
                trigger: "change"
              }
            ],
            tip: "建议尺寸：1920x400像素，大小不超过5MB",
            action: "/api/admin/common/upload",
            accept: "image/*",
            headers: {
              Authorization: `Bearer ${localStorage.getItem("token") || ""}`,
            },
            uploadAfter: (file, done) => {
              // 从file.file属性获取文件路径
              if (file && file.file) {
                const imageUrl = this.formatImageUrl(file.file);
                file.url = imageUrl;
                this.$message.success('上传成功');
                done();
              } else if (file && file.response) {
                const res = file.response;

                if (res.err === 0) {
                  const imageUrl = this.formatImageUrl(res.data.file);
                  file.url = imageUrl;
                  this.$message.success('上传成功');
                  done();
                } else {
                  this.$message.error(res.msg || "上传失败");
                  done();
                }
              } else {
                this.$message.error("上传失败");
                done();
              }
            },
            beforeUpload: (file) => {
              const isLt5M = file.size / 1024 / 1024 < 5;
              if (!isLt5M) {
                this.$message.error("上传图片大小不能超过 5MB!");
                return false;
              }

              const isImage = ['image/jpeg', 'image/png', 'image/gif'].includes(file.type);
              if (!isImage) {
                this.$message.error("只能上传图片文件!");
                return false;
              }

              return true;
            },
          },
          {
            label: "banner位置",
            prop: "ident",
            type: "select",
            align: "center",
            dicData: [
              { label: "首页头部", value: 1 },
              { label: "首页底部", value: 2 },
            ],
            rules: [
              {
                required: true,
                message: "请选择banner位置",
                trigger: "blur",
              },
            ],
          },
          {
            label: "跳转链接",
            prop: "image_full",
            type: "input",
            align: "center",
            placeholder: "请输入跳转链接",
            rules: [
              {
                required: true,
                message: "请输入跳转链接",
                trigger: "blur",
              },
              {
                type: "url",
                message: "请输入正确的URL地址",
                trigger: ["blur", "change"],
              },
            ],
          },
          {
            label: "创建时间",
            prop: "created_at",
            type: "datetime",
            align: "center",
            format: "yyyy-MM-dd HH:mm:ss",
            valueFormat: "yyyy-MM-dd HH:mm:ss",
            addDisplay: false,
            editDisplay: false,
            span: 12,
          },
          {
            label: "展示顺序",
            prop: "sort",
            type: "number",
            align: "center",
            min: 0,
            max: 999,
            span: 12,
            rules: [
              {
                required: true,
                message: "请输入展示顺序",
                trigger: "blur",
              },
            ],
          },
          {
            label: "上架状态",
            prop: "status",
            align: "center",
            type: "radio",
            dicData: [
              { label: "未上架", value: 0 },
              { label: "已上架", value: 1 },
              { label: "已下架", value: 2 },
            ],
            slot: true,
            addDisplay: false,
            editDisplay: false,
            search: true,
            searchSpan: 6,
            searchLabelWidth: 120,
            searchPlaceholder: "请选择banner上架状态（默认不限）",
          },
        ],
      },
    };
  },
  methods: {
    getList (page, params) {
      this.loading = true;
      getBannerList(
        Object.assign(
          {
            page: page.currentPage,
            size: page.pageSize,
          },
          params
        )
      )
        .then((res) => {
          this.data = res.data.list.map((item) => ({
            ...item,
            image: item.image ? this.formatImageUrl(item.image) : "",
          }));
          this.page.total = res.data.total;
        })
        .catch((err) => {
          console.error("获取列表失败:", err);
          this.$message.error("获取列表失败");
        })
        .finally(() => {
          this.loading = false;
        });
    },

    formatImageUrl (url) {
      if (!url) return '';
      if (url.startsWith("http")) {
        return url;
      }
      return `https://api.mszcdf.cn/${url}`;
    },

    // 新增
    handleAdd (row, done, loading) {
      if (!row.image) {
        this.$message.error("请上传图片");
        loading();
        return;
      }

      const addData = {
        ...row,
        image: row.image.startsWith('http') ? row.image : this.formatImageUrl(row.image),
        status: 0, // 默认未上架状态
        created_at: new Date().toISOString()
      };

      addBanner('', addData)
        .then((res) => {
          this.$message.success("添加成功");
          // 重新请求列表数据
          this.getList(this.page);
          done();
        })
        .catch((err) => {
          console.error("添加失败:", err);
          this.$message.error("添加失败: " + (err.message || ""));
          loading();
        });
    },

    // 删除
    handleDel (row) {
      this.$confirm("确定删除该banner吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return delBanner(row.id);
        })
        .then(() => {
          this.$message.success("删除成功");
          // 重新请求列表数据
          this.getList(this.page);
        })
        .catch((err) => {
          if (err !== "cancel") {
            console.error("删除失败:", err);
            this.$message.error("删除失败");
          }
        });
    },

    // 更新
    handleUpdate (row, index, done, loading) {
      const updateData = {
        ...row,
        image: row.image.startsWith('http') ? row.image : this.formatImageUrl(row.image)
      };
      addBanner(row.id, updateData)
        .then(() => {
          this.$message.success("修改成功");
          // 重新请求列表数据
          this.getList(this.page);
          done();
        })
        .catch((err) => {
          console.error("更新失败:", err);
          this.$message.error("更新失败: " + (err.message || ""));
          loading();
        });
    },

    // 状态切换
    handleStatus (row) {
      const newStatus = row.status === 1 ? 2 : row.status === 2 ? 0 : 1;
      const statusText = {
        0: "未上架",
        1: "已上架",
        2: "已下架"
      };
      const actionText = `设为${statusText[newStatus]}`;

      this.$confirm(`确定${actionText}该banner吗?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return updateBanner({
            id: row.id,
            status: newStatus,
          });
        })
        .then(() => {
          this.$message.success(`${actionText}成功`);

          // 重新请求列表数据
          this.getList(this.page);
        })
        .catch((error) => {
          if (error !== "cancel") {
            console.error("更新状态失败:", error);
            this.$message.error(
              `${actionText}失败: ${error.message || "服务器错误"}`
            );
          }
        });
    },

    refreshChange () {
      this.page.currentPage = 1;
      this.getList(this.page);
    },

    handleEdit (row) {
      const fullRowData = this.data.find((item) => item.id === row.id);
      this.$refs.crud.rowEdit(fullRowData, row.$index);
    },
  },
};
</script>

<style scoped>
.el-image {
  border: 1px solid #eee;
  border-radius: 4px;
  height: 60px;
}

.image-slot {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #909399;
  font-size: 12px;
}

.image-slot i {
  font-size: 24px;
  margin-bottom: 5px;
}
</style>